package com.itheima.aspect;

import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class LoginAspect {

    @Autowired
    private LoginMapper loginMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = null;
        try {
            result = pjp.proceed();
        } finally {
            long end = System.currentTimeMillis();
            long costTime = end - start;

            EmpLoginLog empLoginLog = new EmpLoginLog();
            log.info("登录参数{}", pjp.getArgs());
            Object[] args = pjp.getArgs();
            Emp emp = (Emp) args[0];
            empLoginLog.setUsername(emp.getUsername());
            empLoginLog.setPassword(emp.getPassword());
            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setCostTime(costTime);

            Result re = (Result) result;
            LoginInfo loginInfo = (LoginInfo) re.getData();
            if (loginInfo == null) {
                empLoginLog.setIsSuccess((short) 0);
            } else {
                empLoginLog.setIsSuccess((short) 1);
                empLoginLog.setJwt(loginInfo.getToken());
            }

            loginMapper.insert(empLoginLog);
        }

        return result;
    }
}
